#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include<stdlib.h>

#define KEY 6
char *keyword[KEY] = {"for", "if", "then", "else", "while", "do"};
char *op[15]={"+","-","*","/",":",":=","<","<>","<=",">",">=","=",";","(",")"};
char id[1024];
int num;
int token;

void lexical(FILE *fp) {
	char x = getc(fp);
	int i,j;
	memset(id,0,sizeof(id));
	
    while(x==' ' || x=='\n' || x=='\t')
    {
        x=getc(fp);
    }

    if(x>='A'&&x<='Z' || x>='a'&&x<='z')
    {
        for(i=0;x>='A'&&x<='Z' || x>='a'&&x<='z' || x>='0'&&x<='9';i++){
           id[i]=x;
           x=getc(fp);
        }
        ungetc(x, fp);
        strcat(id, "\0");
	   for(j=0;j<KEY;j++)
       {
           if(strcmp(id,keyword[j])==0)
           {
               token=j+1;
               return;
           }
       }
       token=10;
       return;
    }

    else if(x>='0'&&x<='9')
    {
        for(i=0;x>='0'&&x<='9';i++){
           id[i]=x;
           x=getc(fp);
        }
        ungetc(x, fp);
        strcat(id, "\0");
        num=atoi(id);
        token=11;
        return;
    }
    else if(x==':'||x=='='||x=='+'||x=='-'||x=='*'||x=='/'||x=='<'||x=='>'||x==';'||x=='('||x==')')
    {
        for(i=0;x==':'||x=='='||x=='+'||x=='-'||x=='*'||x=='/'||x=='<'||x=='>'||x==';'||x=='('||x==')';i++){
           id[i]=x;
           x=getc(fp);
        }
        ungetc(x, fp);
        strcat(id, "\0");
        for(j=0;j<6;j++)
       {
            if(strcmp(id,op[j])==0)
            {
                token=j+13;
                return;
            }
        }
        for(j=6;j<15;j++)
        {
            if(strcmp(id,op[j])==0)
            {
                token=j+14;
                return;
            }
        }
    }
    else if(x=='#')
    {
        token=0;
	strcpy(id,"#");
        return;
    }
}

int main(int argc, const char *argv[])
{
	if(argc < 2) {
		printf("insufficient args\n");
		return 1;
	}
	FILE *fp = fopen(argv[1], "r");
	do {
		lexical(fp);
		switch(token) {
			case 10: printf("(id, %s)\n", id); break;
			case 11: printf("(num, %d)\n", num); break;
			case -1: printf("error!\n"); break;
			default: printf("(%d, %s)\n", token, id);break;
		}
	} while(token != 0);

	fclose(fp);
	return 0;
}
